import { NavBar, DatePicker } from "antd-mobile";
import classNames from "classnames";
import { useEffect, useMemo, useState } from "react";
import dayjs from "dayjs";
import { useSelector } from "react-redux";
import "./index.scss";
import _ from "lodash";
import DailyBill from "@/components/DailyBill";

const Month = () => {
  // 控制弹框的打开和关闭
  const [dateVisible, setDateVisible] = useState(false);

  //获取当前年月
  const [currentDate, setCurrentDate] = useState(() =>
    dayjs(new Date()).format("YYYY-MM")
  );

  //获取状态管理中的billList
  const billList = useSelector((state) => state.bill.billList);

  //useMemo计算属性 获取按照月份分类的数据对象
  const monthGroupData = useMemo(() => _.groupBy(billList, (item) => dayjs(item.date).format("YYYY-MM")), [billList]);
  

  /**
   * 方案一 统计支出 收入 结余总数， 使用useMemo 计算属性缓存
  */
  const [currentMonthList, setCurrentMonthList] = useState([]) //来获取当前月份对应的的记录数组

  const monthResult = useMemo(() => {
    return currentMonthList.reduce((pre, next) => {
        if (next.type === "income") {
            pre.income = next.money + pre.income;
          } else if (next.type === "pay") {
          pre.pay = next.money + pre.pay;
        }
        pre.total = next.money + pre.total;
        return pre;
      }, { pay: 0, income: 0, total: 0 });
  },[currentMonthList])


  /**
   * 方案二  统计支出 收入 结余总数 使用函数封装 和 定义对象的方式
  */
  const [monthResult1, setMonthResult1] = useState({
    pay: 0,
    income: 0,
    total: 0,
  });

  //封装方法里统一计算
  const getFilterTotal = (dateMonth) => {
    const dataArr = monthGroupData[dateMonth];
    const res = dataArr && dataArr.reduce((pre, next) => {
          if (next.type === "income") {
              pre.income = next.money + pre.income;
            } else if (next.type === "pay") {
            pre.pay = next.money + pre.pay;
          }

          pre.total = next.money + pre.total;
          
          return pre;
        }, { pay: 0, income: 0, total: 0 });
      res && setMonthResult1({...monthResult1,...res})
  }


  //选择月份确定
  const onConfirm = (value) => {
    const formatDate = dayjs(value).format("YYYY-MM");
    //方案二的写法
    // getFilterTotal(formatDate);

    //方案一的写法
    setCurrentMonthList(monthGroupData[currentDate])

    setCurrentDate(formatDate);
    setDateVisible(false);
  };

  useEffect(() => {
    // getFilterTotal(currentDate) //方案二的写法
    const currentValue = monthGroupData[currentDate];
    currentValue && setCurrentMonthList(currentValue) //方案一的写法
  }, [monthGroupData, currentDate]);

  //单日统计列表
  const dayGroup = useMemo(() => {
    const groupData =  _.groupBy(currentMonthList, item => dayjs(item.date).format("YYYY-MM-DD"))
    const keys = Object.keys(groupData);
    return {
      groupData,
      keys
    }
  }, [currentMonthList])
  console.log(dayGroup);
  
  return (
    <div className="monthlyBill">
      <NavBar className="nav" backArrow={false}>
        月度收支
      </NavBar>
      <div className="content">
        <div className="header">
          {/* 时间切换区域 */}
          <div className="date" onClick={() => setDateVisible(true)}>
            <span className="text">{currentDate + ""}月账单</span>
            {/* 思路：根据当前弹框打开的状态控制expand类名是否存在 */}
            <span
              className={classNames("arrow", dateVisible && "expand")}
            ></span>
          </div>
          {/* 统计区域 */}
          <div className="twoLineOverview">
            <div className="item">
              <span className="money">{monthResult.pay.toFixed(2)}</span>
              <span className="type">支出</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.income.toFixed(2)}</span>
              <span className="type">收入</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.total.toFixed(2)}</span>
              <span className="type">结余</span>
            </div>
          </div>
          {/* 时间选择器 */}
          <DatePicker
            className="kaDate"
            title="记账日期"
            precision="month"
            visible={dateVisible}
            onCancel={() => setDateVisible(false)}
            onConfirm={onConfirm}
            onClose={() => setDateVisible(false)}
            max={new Date()}
          />
        </div>
        {/* 单日列表统计 */}
        {dayGroup.keys.map((key) => {
          return (
            <DailyBill
              key={key}
              date={key}
              billList={dayGroup.groupData[key]}
            />
          );
        })}
      </div>
    </div>
  );
};

export default Month;
